// 分类数据的简单前端存储与工具方法（示例用，后续可替换为后端接口）
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

// 初始示例数据：支持多级分类；status: 'enabled' | 'disabled'
const seed = [
  { id: 1, name: 'Java', parentId: 0, level: 1, sort: 1, status: 'enabled', description: 'Java 生态', createdAt: dayjs().subtract(20,'day').toISOString(), updatedAt: dayjs().toISOString() },
  { id: 2, name: 'SpringBoot', parentId: 1, level: 2, sort: 1, status: 'enabled', description: '', createdAt: dayjs().subtract(18,'day').toISOString(), updatedAt: dayjs().toISOString() },
  { id: 3, name: 'MyBatis-Plus', parentId: 1, level: 2, sort: 2, status: 'enabled', description: '', createdAt: dayjs().subtract(18,'day').toISOString(), updatedAt: dayjs().toISOString() },
  { id: 4, name: 'SpringBoot 核心注解', parentId: 2, level: 3, sort: 1, status: 'enabled', description: '', createdAt: dayjs().subtract(15,'day').toISOString(), updatedAt: dayjs().toISOString() },
  { id: 5, name: 'Python', parentId: 0, level: 1, sort: 2, status: 'disabled', description: 'Python 生态', createdAt: dayjs().subtract(10,'day').toISOString(), updatedAt: dayjs().toISOString() },
  { id: 6, name: 'Django', parentId: 5, level: 2, sort: 1, status: 'disabled', description: '', createdAt: dayjs().subtract(9,'day').toISOString(), updatedAt: dayjs().toISOString() }
]

export const categories = ref(seed)

// 构建树形结构数据
export function getTree(list = categories.value) {
  const map = new Map()
  list.forEach(x => map.set(x.id, { ...x, children: [] }))
  const roots = []
  map.forEach(node => {
    if (!node.parentId || node.parentId === 0) {
      roots.push(node)
    } else if (map.has(node.parentId)) {
      map.get(node.parentId).children.push(node)
    } else {
      roots.push(node) // 容错：找不到父则视为根
    }
  })
  // 同层按 sort 升序
  const sortChildren = (arr) => {
    arr.sort((a,b)=> (a.sort ?? 0) - (b.sort ?? 0))
    arr.forEach(ch => ch.children && sortChildren(ch.children))
  }
  sortChildren(roots)
  return roots
}

// 计算指定分类的所有子孙 ID
export function getDescendantIds(id, list = categories.value) {
  const children = list.filter(x => x.parentId === id).map(x => x.id)
  return children.reduce((acc, cid) => acc.concat(cid, getDescendantIds(cid, list)), [])
}

// 是否存在子分类
export function hasChildren(id, list = categories.value) {
  return list.some(x => x.parentId === id)
}

// 示例：是否有关联商品（真实场景应由后端返回统计值）
export function hasLinkedProducts(id) {
  // 这里模拟：id 为 2 或 4 有关联商品
  return [2,4].includes(id)
}

// 新增分类
export function addCategory(payload) {
  const id = Math.max(...categories.value.map(x => x.id)) + 1
  const now = dayjs().toISOString()
  const level = payload.parentId ? ((categories.value.find(x => x.id === payload.parentId)?.level || 0) + 1) : 1
  const item = { id, name: payload.name, parentId: payload.parentId || 0, level, sort: payload.sort ?? 1, status: payload.status || 'enabled', description: payload.description || '', createdAt: now, updatedAt: now }
  categories.value.push(item)
  return item
}

// 更新分类
export function updateCategory(id, payload) {
  const idx = categories.value.findIndex(x => x.id === id)
  if (idx === -1) return
  const now = dayjs().toISOString()
  const parentId = payload.parentId ?? categories.value[idx].parentId
  const level = parentId ? ((categories.value.find(x => x.id === parentId)?.level || 0) + 1) : 1
  categories.value[idx] = { ...categories.value[idx], ...payload, parentId, level, updatedAt: now }
}

// 删除分类（若存在子分类或关联商品则返回 false）
export function deleteCategory(id) {
  if (hasChildren(id) || hasLinkedProducts(id)) return false
  categories.value = categories.value.filter(x => x.id !== id)
  return true
}

// 批量更新状态
export function batchSetStatus(ids, status) {
  categories.value = categories.value.map(x => ids.includes(x.id) ? { ...x, status } : x)
}

export const treeComputed = computed(() => getTree())